package com.elin4it.blog.controller;

import com.elin4it.blog.controller.exception.BlogException;
import com.elin4it.blog.pojo.Article;
import com.elin4it.blog.pojo.ArticleCustom;
import com.elin4it.blog.pojo.ArticleType;
import com.elin4it.blog.service.ArticleService;
import com.elin4it.blog.service.ArticleTypeService;
import com.elin4it.blog.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

/**
 * User:Elin
 * Date:2015/7/16
 * Description:
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private ConfigService configService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private Properties config;

    private final String flag = "blog";

    /**
     * 把一些公共的信息放入modelmap中
     *
     * @param map
     * @throws Exception
     */
    @ModelAttribute
    public void commonMessage(ModelMap map) throws Exception {
        //得到标题和副标题
        String title = configService.findTitle();
        String subTitle = configService.findSubTitle();

        //把标题和副标题放入到model中
        map.put("title", title);
        map.put("subtitle", subTitle);
        //设置页面标识
        map.put("flag", flag);
    }



    @RequestMapping("/blog")
    public String blog(ModelMap modelMap, @RequestParam(value = "id", required = true) Integer id) throws Exception {
        //调用service查询文章
        ArticleCustom article = articleService.findArticle(id);
        if (article == null || article.getId() == null) {
            throw new BlogException(config.getProperty("blogNotFound"));
        }
        modelMap.put("article", article);

        return "blog/blog";
    }

    /**
     * 显示所有的博客列表
     *
     * @param modelMap
     * @param pageNum  当前页码
     * @return
     * @throws Exception
     */
    @RequestMapping("/allBlog")
    public String allBlog(ModelMap modelMap,
                          @RequestParam(value = "pageNum", required = false) Integer pageNum,
                          @RequestParam(value = "type", required = false) Integer type) throws Exception {
        // 如果没有传递页码，则默认为第一页
        if (pageNum == null)
            pageNum = 1;
        //如果没有传递类型，则置为0
        if (type == null)
            type = 0;
        //从配置文件中获取每页的记录数
        Integer pageCount = Integer.parseInt(config.getProperty("pageCount"));
        //得到当前页码的列表
        List<ArticleCustom> list = null;
        //进行查找
        list = articleService.findArticlePagingWithArticleType(pageNum, pageCount, type);
        modelMap.put("articles", list);

        //得到总页数
        Integer allPageCount = articleService.pageNum(type);
        modelMap.put("allPageCount", allPageCount);

        //判断是否有上一页和下一页
        boolean hasPervious = !(pageNum == 1);
        boolean hasNext = !(pageNum == allPageCount);
        modelMap.put("hasPervious", hasPervious);
        modelMap.put("hasNext", hasNext);

        //传递当前页码
        modelMap.put("pageNum", pageNum);
        //传递当前类型
        modelMap.put("type", type);

        //获得所有的文章类别
        List<ArticleType> articleTypeList = articleTypeService.findArticleTypeList();
        modelMap.put("articleTypeList", articleTypeList);

        return "blog/allBlog";
    }

    @RequestMapping("/uploadImage")
    public void uploadImage(@RequestParam("upload") MultipartFile multipartFile, @RequestParam("CKEditorFuncNum") String CKEditorFuncNum, HttpServletRequest request, PrintWriter out) throws Exception {
        //        遍历数组中的多个文件，示例jsp页面为只上传一个文件


        String path = request.getContextPath() + config.getProperty("imageUploadPath");
//            获取原始图片名称
        String oldFileName = multipartFile.getOriginalFilename();
//            设置随机的图片名称
        String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));

//            创建新的文件
        File file = new File("/image/abc.jpg");

//            把内存中的图片写入对应的目录
        multipartFile.transferTo(file);

        String s = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                + ",'" + request.getContextPath() + "/img/uploadImg/" + path + newFileName + "','')</script>";
        out.print(s);
    }
}
